package com.mengtian_tech.tju.dataquery.api.config.interceptors;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpStatus;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.ImmutableMap;
import com.mengtian_tech.tju.dataquery.api.util.SessionUtil;
import com.mengtian_tech.tju.dataquery.api.util.SpringUtil;

public class AjaxInterceptor implements HandlerInterceptor{

	
	/**
	 * 判断当前用户是否登录，如果没有登录，返回401，并且返回cas登录地址
	 * 登录成功后跳转地址默认为“/”，会被CAS拦截，并登录成功
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		
		String clientType = request.getHeader("clinet-type");
		if(StringUtils.isNotEmpty(clientType)) {
			System.out.println("client type:"+clientType);
			SessionUtil.setClientType(Integer.parseInt(clientType));
		}
		
		
		//放过测试地址
		if(request.getRequestURI().contains("/api/emp/")) {
			return HandlerInterceptor.super.preHandle(request, response, handler); 
		}
		
	/*	if(request.getRequestURI().contains("/api")) { //测试，都放过。
			return HandlerInterceptor.super.preHandle(request, response, handler); 
		}
		*/
		
		//获取cas登录成功后的user
		String user = SessionUtil.getUser();
		if(StringUtils.isEmpty(user)) {//未登录
			
			//获取cas信息
			Environment env =  SpringUtil.getContext().getBean(Environment.class);
	    	String service = env.getProperty("cas.service.host.url");
	    	String loginUrl = env.getProperty("cas.server.host.login_url");
			
			String callbackURL = request.getHeader("pageurl");
			SessionUtil.setCallbackURL(callbackURL);
			
			System.out.println("not login,url="+request.getRequestURL());
			
			//发送未登录信息
			send401(response, service, loginUrl);
			
			return false;
		}
		
		return HandlerInterceptor.super.preHandle(request, response, handler);
	}

	private void send401(HttpServletResponse response, String service, String loginUrl) throws IOException {
		//设置401
		response.setStatus(HttpStatus.UNAUTHORIZED.value());
		//响应数据
		Map<String, Object> data = ImmutableMap.<String, Object>builder()
		        .put("errorType", "NOT_LOGIN_CAS")
		        .put("casLoginUrl", loginUrl + "?service="+service+"/login")
		        .build();
		//输出
		PrintWriter out = response.getWriter();
		out.println(JSON.toJSONString(data));
		out.flush();
		out.close();
	}

}
